# -*- coding:utf-8 -*-

"""
    设备sn_id管理，主要用于测试设备
"""

import tornado.gen
from service import base
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config


# 存放测试使用的所有sn_id
TOTAL_TEST_SN_IDS = []

@tornado.gen.engine
def loadSnIds():
    """ 加载数据库里的sn_ids
    """
    sn_ids_saved = yield tornado.gen.Task(mongo.distinct, config.DB_NAME, config.COLLECTION_SN_ID, 'sn_id')
    global TOTAL_TEST_SN_IDS
    TOTAL_TEST_SN_IDS = sn_ids_saved


@route('/manage/sn_id/?', 'manage.sn_id')
class SnIdsHandler(base.BaseWebHandler):
    """ 管理测试 sn_id
    """
    db_name = config.DB_NAME
    collection_sn_id = config.COLLECTION_SN_ID

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        key = 'sn_id'
        sn_ids = yield tornado.gen.Task(mongo.distinct, self.db_name, self.collection_sn_id, key)
        logger.debug('sn_ids = ', sn_ids, caller=self)
        sn_ids_str = ''
        for sn_id in sn_ids:
            sn_ids_str += (sn_id + '\n')
        self.render('manage/sn_id.html', sn_ids_str=sn_ids_str)

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self, *argl, **argd):
        sn_ids_str = self.get_argument('sn_ids', None)
        if not sn_ids_str:
            self.finish({'code': 1, 'info': '请添加sn_id！'})
            return
        
        sn_ids = [ sn_id.strip() for sn_id in sn_ids_str.split(';')]
        key = 'sn_id'
        sn_ids_saved = yield tornado.gen.Task(mongo.distinct, self.db_name, self.collection_sn_id, key)
        logger.info('sn_ids =', sn_ids, 'sn_ids_saved =', sn_ids_saved, caller=self)
        for sn_id in sn_ids:
            if sn_id in sn_ids_saved:
                continue
            spec = {'sn_id': sn_id}
            yield tornado.gen.Task(mongo.insert, self.db_name, self.collection_sn_id, spec)
        for sn_id in sn_ids_saved:
            if sn_id in sn_ids:
                continue
            spec = {'sn_id': sn_id}
            yield tornado.gen.Task(mongo.remove, self.db_name, self.collection_sn_id, spec)
        
        loadSnIds()
        self.finish({'code': 0, 'info': '更新成功！'})

